//
//  AdAndHint.m
//  IconMaster
//
//  Created by 为为 on 14-9-26.
//  Copyright (c) 2014年 为为. All rights reserved.
//

#import "AdAndHint.h"
#import "UIAlertView+Blocks.h"
#import "DBOperation.h"

#define INTERSTITIAL_NUM 4
static GADInterstitial* interstitialArray[INTERSTITIAL_NUM] = {NULL};

@interface AdAndHint ()

@end

@implementation AdAndHint

+ (AdAndHint*)sharedInstance
{
	static dispatch_once_t onceToken;
	static AdAndHint* instance = nil;
	dispatch_once(&onceToken, ^{
		instance = [[AdAndHint alloc] init];
	});
	
	return instance;
}

+ (void)showGetFullVersionHint
{
	[UIAlertView showWithTitle:nil
					   message:NSLocalizedString(@"Download full version to get rid of annoying ad", @"")
			 cancelButtonTitle:NSLocalizedString(@"Cancel", @"")
			 otherButtonTitles:@[NSLocalizedString(@"OK", @"")]
					  tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
						  if (buttonIndex == alertView.cancelButtonIndex) {
							  
						  } else {
							  dispatch_async(dispatch_get_main_queue(), ^{
								  NSURL* url = [NSURL URLWithString:@"http://itunes.apple.com/app/id663420081"];
								  [[UIApplication sharedApplication] openURL:url];
							  });
						  }
					  }];
}

+ (GADBannerView*)getBannerView:(int*)firstCreate
{
	@synchronized(self) {
		GADBannerView* bannerView = nil;
		if (/* DISABLES CODE */ (1)) {
			bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner];
//            [Files_New getADID:^(NSDictionary *dictADID) {
//            bannerView.adUnitID = dictADID[@"iosBannerAdId"];//*/ [DBOperation admobID];
//
//            }];
            bannerView.adUnitID = [Files_New readFiles][@"iosBannerAdId"];
//           ba             NSLog(@"********[DBOperation admobID] =%@***********/n***********[Files_New fffff][@bannerAdId]%@*********",[DBOperation admobID],[Files_New fffff][@"bannerAdId"]);
			if (firstCreate) {
				*firstCreate = 1;
			}
		} else {
			if (firstCreate) {
				*firstCreate = 0;
			}
		}
		return bannerView;
	}
}

+ (GADBannerView*)showBannerViewInController:(UIViewController *)contoller view:(UIView *)view frame:(CGRect)frame
{
	int fristCreate = 0;
	GADBannerView* bannerView = [self getBannerView:&fristCreate];
	bannerView.rootViewController = contoller;
	bannerView.frame = CGRectMake(frame.origin.x, frame.origin.y, bannerView.frame.size.width, bannerView.frame.size.height);
    bannerView.tag = 0xad;
	[view addSubview:bannerView];
	
	if (fristCreate) {
    	GADRequest* request = [GADRequest request];
//    	request.testDevices = [NSArray arrayWithObjects:GAD_SIMULATOR_ID, @"06b91b9e8c45ccaaa46e44066dcf7c1f", nil];
    	[bannerView loadRequest:request];
	}
	
	return bannerView;
}

+ (void)loadInterstitialIfNeed
{
	for (int i=0; i<INTERSTITIAL_NUM; i++) {
		if (!interstitialArray[i]) {
			GADInterstitial* interstitial_;
			interstitial_ = [[GADInterstitial alloc] init];
//            [Files_New getADID:^(NSDictionary *dictADID) {
//                     interstitial_.adUnitID = dictADID[@"iosInterstitialAdId"]; //[DBOperation admobPageID];
//            }];
       
            interstitial_.adUnitID = [Files_New readFiles][@"iosInterstitialAdId"];
			interstitial_.delegate = [self sharedInstance];
			interstitialArray[i] = interstitial_;
			
//			GADRequest* request = [GADRequest request];
//			request.testDevices = @[ @"3d7a9b084da802c862a283b1ddf4cc4c"];
			[interstitial_ loadRequest:[GADRequest request]];
			NSLog(@"request interstitial %d", i);
		}
	}
}

+ (void)showInterstitialViewInController:(UIViewController *)controller
									withRatioPercent:(int)ration
{
	BOOL needToLoad = YES;
	for (int i=0; i<INTERSTITIAL_NUM; i++) {
		if (interstitialArray[i] && interstitialArray[i].isReady) {
//			ration = 100;
			needToLoad = NO;
			int random = arc4random()%100;
			if (random>ration) {
				return;
			}
			
			[interstitialArray[i] presentFromRootViewController:controller];
			break;
			NSLog(@"present interstitial %d", i);
		}
	}
	
	if (needToLoad) {
		[self loadInterstitialIfNeed];
	}
}

#pragma mark interstital delegate

- (void)interstitialDidReceiveAd:(GADInterstitial *)ad
{
	for (int i=0; i<INTERSTITIAL_NUM; i++) {
		if (interstitialArray[i] == ad) {
        	NSLog(@"interstitial receive ad %d", i);
		}
	}
}

- (void)interstitial:(GADInterstitial *)ad didFailToReceiveAdWithError:(GADRequestError *)error
{
	BOOL needReload = NO;
	for (int i=0; i<INTERSTITIAL_NUM; i++) {
		if (interstitialArray[i] == ad) {
			interstitialArray[i] = NULL;
			if (i == 0) {
				needReload = YES;
			}
        	NSLog(@"interstitial fail receive ad %d", i);
		}
	}
	
	if (needReload) {
		[AdAndHint performSelector:@selector(loadInterstitialIfNeed) withObject:nil afterDelay:5];
	}
}

- (void)interstitialDidDismissScreen:(GADInterstitial *)ad
{
	for (int i=0; i<INTERSTITIAL_NUM; i++) {
		if (interstitialArray[i] == ad) {
			interstitialArray[i] = NULL;
        	NSLog(@"interstitial dismissed %d", i);
		}
	}
	
	[AdAndHint loadInterstitialIfNeed];
}

@end
